﻿Imports SistemaINCA.Controllers
Imports SistemaINCA.Models
Imports SistemaINCA.Models.ViewModels
Imports System.Globalization

Imports SistemaINCA.Security
Imports System.Net

Namespace Controllers
    Public Class AEscolarController
        Inherits BaseController

#Region "TODOS LOS METODOS UTILIZADOS PARA EL MENUITEM 'DEFINIR_ANIO_ASUETOS'"

        <Authorize(Roles:="ERA")> _
        Function Definir_Anio_Asuetos() As ActionResult
            'Dim db As New SchoolClickDB_Repositorio
            'Try
            '    'Recuperamos el ultimo año escolar que posea el instituto
            '    ViewBag.AñoEscolar = db.GET_LAST_AÑO_ESCOLAR(1)
            '    ViewBag.Min_AñoEscolar = db.GET_MIN_AÑO_ESCOLAR_BY_INSTITUTO(1)
            '    Return View()
            'Catch ex As Exception
            '    Throw New Exception(ex.Message, ex)
            'End Try
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpGet()> _
        Function _Info_Anio_Escolar(AE As String) As ActionResult
            If Request.IsAjaxRequest Then
                'Dim db As New SchoolClickDB_Repositorio
                'Try
                '    'Limpiamos la cadena que no venga codigo JavaScript maligno
                '    Dim año As String = HttpUtility.HtmlEncode(AE)

                '    If Not año.Equals("ERROR") Then
                '        Return PartialView(db.GET_AÑO_ESCOLAR(1, año))
                '    End If
                'Catch ex As Exception
                '    Throw New Exception(ex.Message, ex)
                'End Try
            Else
                Return RedirectToAction("Definir_Anio_Asuetos")
            End If
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpGet()> _
        Function _Edit_AE(AE As Integer) As ActionResult
            If Request.IsAjaxRequest Then
                'Dim db As New SchoolClickDB_Repositorio
                'Try
                '    Dim info_ae = db.GET_AÑO_ESCOLAR(1, AE)
                '    Dim editModel = New ViewModels.EditFechasAEModel With {.Anio = info_ae.ID_ANIO_ESCOLAR, .FInicio = info_ae.F_INICIO.ToString("dd/MM/yyyy"), .FFinal = info_ae.F_FINAL.ToString("dd/MM/yyyy")}
                '    ViewBag.EditMode = True
                '    Return PartialView("_EditFechasAE", editModel)
                'Catch ex As Exception
                '    Throw New Exception(ex.Message, ex)
                'End Try
            Else
                Return RedirectToAction("Definir_Anio_Asuetos")
            End If
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpGet()> _
        Function _New_AE() As ActionResult
            If Request.IsAjaxRequest Then
                Try
                    Dim newModel = New EditFechasAEModel With {.Anio = Date.Now.Year}
                    ViewBag.EditMode = False
                    Return PartialView("_EditFechasAE", newModel)
                Catch ex As Exception
                    Throw New Exception(ex.Message, ex)
                End Try
            Else
                Return RedirectToAction("Definir_Anio_Asuetos")
            End If
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function POST_Save_Changes_Fechas_AE(model As Models.ViewModels.EditFechasAEModel) As ActionResult
            If ModelState.IsValid Then
                'Dim db As New SchoolClickDB_Repositorio
                'Dim errMsj As String = String.Empty

                ''Llamamos al procedimiento para almacenar los datos en el servidor
                'Dim a = db.UPDATE_ANIOESCOLARES_FECHAS(model.Anio, _
                '                                   Date.ParseExact(model.FInicio, "dd/MM/yyyy", CultureInfo.GetCultureInfo("es-SV")), _
                '                                   Date.ParseExact(model.FFinal, "dd/MM/yyyy", CultureInfo.GetCultureInfo("es-SV")), _
                '                                   errMsj)

                ''Comprobamos si se ejecuto correctamente
                'If a Then
                '    'Los cambios se guardaron satisfactoriamente en el servidor, por lo tanto regresaremos la pagina principal
                '    'de la definicion del año escolar
                '    Return PartialView("_TempCloseUIDialog", model)
                'Else
                '    'Devolvemos la vista parcial con el error devuelto por la operacion de "SAVE"
                '    ModelState.AddModelError("ErrorDB", errMsj)
                'End If
            End If
            ViewBag.EditMode = True
            Return PartialView("_EditFechasAE", model)
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function POST_Create_New_AE(model As Models.ViewModels.EditFechasAEModel) As ActionResult
            If ModelState.IsValid Then
                'Dim db As New SchoolClickDB_Repositorio
                'Dim errMsj As String = String.Empty

                ''Llamamos al procedimiento para almacenar los datos en el servidor
                'Dim a = db.INSERT_NEW_ANIOESCOLAR(model.Anio, _
                '                                   Date.ParseExact(model.FInicio, "dd/MM/yyyy", CultureInfo.GetCultureInfo("es-SV")), _
                '                                   Date.ParseExact(model.FFinal, "dd/MM/yyyy", CultureInfo.GetCultureInfo("es-SV")), _
                '                                   errMsj)

                ''Comprobamos si se ejecuto correctamente
                'If a Then
                '    'Los cambios se guardaron satisfactoriamente en el servidor, por lo tanto regresaremos la pagina principal
                '    'de la definicion del año escolar
                '    Return PartialView("_TempCloseUIDialog", model)
                'Else
                '    'Devolvemos la vista parcial con el error devuelto por la operacion de "SAVE"
                '    ModelState.AddModelError("ErrorDB", errMsj)
                'End If
            End If
            ViewBag.EditMode = False
            Return PartialView("_EditFechasAE", model)
        End Function

#Region "CRUDA DE LA TABLA DE 'ASUETOS' DEL MENUITEM 'DEFINIR_AÑO_ESCOLAR'"
        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function _Load_ListAsuetos(AE As Integer) As JsonResult
            'Try
            '    Dim db As New SchoolClickDB_Repositorio
            '    Return Json(New With {.Result = "OK", .Records = db.GET_LISTADO_DIAS_ASUETOS(AE)})
            'Catch ex As Exception
            '    Return Json(New With {.Result = "ERROR", .Message = ex.Message})
            'End Try
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function _Delete_ItemAsueto(IDAsueto As String) As JsonResult
            'Try
            '    'Lo primero es descomponer el IDAsueto a IDRegistro y Año
            '    Dim separator As Char() = {"-"}
            '    Dim stringSeparado As String() = IDAsueto.Split(separator)
            '    Dim db As New SchoolClickDB_Repositorio
            '    Dim msjError As String = String.Empty
            '    Dim bRes As Boolean = db.DELETE_REGISTRO_ASUETO(stringSeparado(1), stringSeparado(0), msjError)
            '    If bRes Then
            '        Return Json(New With {.Result = "OK"})
            '    Else
            '        Return Json(New With {.Result = "ERROR", .Message = msjError})
            '    End If
            'Catch ex As Exception
            '    Return Json(New With {.Result = "ERROR", .Message = ex.Message})
            'End Try
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function _New_ItemAsueto(model As DiaAsuetoModel) As JsonResult
            'Try
            '    If Not ModelState.IsValid Then
            '        Return Json(New With {.Result = "ERROR", _
            '                              .Message = My.Resources.ErrorMessageResources.Error_InvalidForm})
            '    Else
            '        Dim db As New SchoolClickDB_Repositorio
            '        Dim msjError As String = String.Empty
            '        Dim a = db.INSERT_REGISTRO_ASUETO(Date.ParseExact(model.FechaInicio, "dd/MM/yyyy", CultureInfo.GetCultureInfo("es-SV")), _
            '                                          Date.ParseExact(model.FechaFinal, "dd/MM/yyyy", CultureInfo.GetCultureInfo("es-SV")), _
            '                                          model.Descripcion, msjError)
            '        If a Then
            '            Dim AddedRecord = model
            '            Return Json(New With {.Result = "OK", .Record = AddedRecord})
            '        Else
            '            Return Json(New With {.Result = "ERROR", .Message = msjError})
            '        End If
            '    End If
            'Catch ex As Exception
            '    Return Json(New With {.Result = "ERROR", .Message = ex.Message})
            'End Try
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function _Update_ItemAsueto(model As DiaAsuetoModel) As JsonResult
            'Try
            '    If Not ModelState.IsValid Then
            '        Return Json(New With {.Result = "ERROR", _
            '                              .Message = My.Resources.ErrorMessageResources.Error_InvalidForm})
            '    Else
            '        Dim db As New SchoolClickDB_Repositorio
            '        Dim separator As Char() = {"-"}
            '        Dim stringSeparado As String() = model.IDAsueto.Split(separator)
            '        Dim msjError As String = String.Empty
            '        Dim a = db.UPDATE_REGISTRO_ASUETO(CInt(stringSeparado(0)), _
            '                                          Date.ParseExact(model.FechaInicio, "dd/MM/yyyy", CultureInfo.GetCultureInfo("es-SV")), _
            '                                          Date.ParseExact(model.FechaFinal, "dd/MM/yyyy", CultureInfo.GetCultureInfo("es-SV")), _
            '                                          model.Descripcion, msjError)
            '        If a Then
            '            Return Json(New With {.Result = "OK"})
            '        Else
            '            Return Json(New With {.Result = "ERROR", .Message = msjError})
            '        End If
            '    End If
            'Catch ex As Exception
            '    Return Json(New With {.Result = "ERROR", .Message = ex.Message})
            'End Try
        End Function
#End Region

#End Region

#Region "TODOS LOS METODOS UTILIZADOS PARA EL MENUITEM 'PERIODOS_EVALUACION'"
        <Authorize(Roles:="ERA")> _
        Function Periodos_Eva() As ActionResult
            'Dim db As New SchoolClickDB_Repositorio
            Try
                '    'DETERMINAMOS EL PERIODO ACTIVO DEL SISTEMA
                '    ViewBag.PA = db.IPeriodos.GetPeriodoActivo

                '    'RECUPERAMOS EL LISTADO DE PERIODOS DEL SISTEMA
                '    ViewBag.ListPeriodos = db.IPeriodos.GetListaPeriodos

                '    'Determinamos el año en el que nos encontramos
                '    Dim strAño = Date.Now.Year.ToString
                '    'Dim strAño = "2009"
                '    ViewBag.AnioP = strAño
                '    ViewBag.ExistenRegistros = db.IPeriodos.ExistsPeriodosByAño(strAño)
                Return View()
            Catch ex As Exception
                Throw New Exception(ex.Message, ex)
            End Try
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function Des_PActivo() As ActionResult
            Dim db As New SchoolClickDB_Repositorio
            Try
                'Dim msjE As String = String.Empty
                'Dim res = db.IPeriodos.OperacionDesactivarPeriodoActivo(msjE)
                'If res Then
                '    Return Json(New With {.Success = True, .Message = "Se ha desactivado correctamente el periodo", .Desactivar = True})
                'Else
                '    Response.StatusCode = HttpStatusCode.InternalServerError
                '    Return Json(msjE)
                'End If
            Catch ex As Exception
                Response.StatusCode = HttpStatusCode.InternalServerError
                Return Json(ex.InnerException.Message)
            End Try
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function Activar_P(P As String) As ActionResult
            Dim db As New SchoolClickDB_Repositorio
            Dim separador As Char() = {"-"}
            Dim datos As String() = P.Split(separador)
            Dim msjE As String = String.Empty

            Try
                'Dim res = db.IPeriodos.OperacionActivarPeriodo(datos(1), datos(0), msjE)
                'If res Then
                '    Return Json(New With {.Success = True, .Message = "Se activó correctamente el periodo", .Desactivar = False, .ReloadPage = True})
                'Else
                '    Response.StatusCode = HttpStatusCode.InternalServerError
                '    Return Json(msjE)
                'End If
            Catch ex As Exception
                Response.StatusCode = HttpStatusCode.InternalServerError
                Return Json(ex.InnerException.Message)
            End Try
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpGet()> _
        Function _CrearPeriodos(Anio As String) As ActionResult
            If Request.IsAjaxRequest Then
                Dim newp = New NewPeriodosModel With {.NoPeriodos = 4}
                ViewBag.AnioP = Anio
                Return PartialView(newp)
            Else
                Return RedirectToAction("Periodos_Eva")
            End If
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function POST_Crear_Periodos_Eva(AnioP As String, NoPeriodos As String) As ActionResult
            'Lo primero sera limpiar las cadenas de cualquier Inject de JavaScript
            Dim strNoP = HttpUtility.HtmlEncode(NoPeriodos)
            Dim strAnio = HttpUtility.HtmlEncode(AnioP)
            Dim iNoP As Integer

            'Verificamos que las validaciones se cumplan de los datos
            If String.IsNullOrWhiteSpace(strNoP) Then
                Response.StatusCode = HttpStatusCode.InternalServerError
                Return Json("El número de periodos no puede quedar vacío.")
            ElseIf Not Integer.TryParse(strNoP, iNoP) Then
                Response.StatusCode = HttpStatusCode.InternalServerError
                Return Json("El valor ingresado no es un número valido. Solo se aceptan numero entre 1 a 9.")
            ElseIf iNoP = 0 OrElse iNoP > 9 Then
                Response.StatusCode = HttpStatusCode.InternalServerError
                Return Json("El valor del campo solo puede ser un numero entre 1 hasta 9.")
            Else
                Dim db As New SchoolClickDB_Repositorio
                'Try
                '    Dim msjE = String.Empty
                '    Dim res = db.IPeriodos.InsertNewPeriodos(strAnio, iNoP, msjE)
                '    If res Then
                '        Return Json(New With {.Success = True, .Message = String.Format("Se crearon correctamente los {0} periodos.", strNoP), .ReloadPage = True})
                '    Else
                '        Response.StatusCode = HttpStatusCode.InternalServerError
                '        Return Json(msjE)
                '    End If
                'Catch ex As Exception
                '    Response.StatusCode = HttpStatusCode.InternalServerError
                '    Return Json(ex.InnerException.Message)
                'End Try
            End If
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function Calcular_PTotal_ActXDefecto() As JsonResult
            'Try
            '    Dim db As New SchoolClickDB_Repositorio
            '    Dim iTotal = db.IActividadesEva.CalcularTotalActividadesDefault_DataTemp
            '    Dim msj = String.Format("Total del Porcentaje de Evaluación: {0}/100 (%)", iTotal)

            '    If iTotal.Equals(100) Then
            '        Return Json(New With {.Result = True, .Mensaje = msj})
            '    Else
            '        Return Json(New With {.Result = False, .Mensaje = msj, _
            '                              .CustomError = String.Format("Por el momento no se pueden guardar los datos, debido a que el Total del Porcentaje es {0} que 100%.", If(iTotal < 100, "menor", "mayor"))})
            '    End If
            'Catch ex As Exception
            '    Response.StatusCode = HttpStatusCode.InternalServerError
            '    Return Json(ex.InnerException.Message)
            'End Try
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function GuardarAllAct() As ActionResult
            'Dim db As New SchoolClickDB_Repositorio
            'Dim msjE As String = String.Empty

            'Try
            '    'Dim res = db.IPeriodos.OperacionActivarPeriodo(datos(1), datos(0), msjE)
            '    If db.IActividadesEva.Save_AllChanges_ActividadesDefault(msjE) Then
            '        Return Json(New With {.Success = True, .Message = "Se guardaron correctamente todos los cambios en las actividades.", .Desactivar = False, .ReloadPage = True})
            '    Else
            '        Response.StatusCode = HttpStatusCode.InternalServerError
            '        Return Json(msjE)
            '    End If
            'Catch ex As Exception
            '    Response.StatusCode = HttpStatusCode.InternalServerError
            '    Return Json(ex.InnerException.Message)
            'End Try
        End Function

#Region "CRUDA PARA LA TABLA DE ACTIVIDADES POR DEFECTO"
        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function _Load_ActividadesDef() As JsonResult
            'Try
            '    Dim db As New SchoolClickDB_Repositorio
            '    Return Json(New With {.Result = "OK", .Records = db.IActividadesEva.GetActividadesDefaultTable})
            'Catch ex As Exception
            '    Return Json(New With {.Result = "ERROR", .Message = ex.Message})
            'End Try
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function _New_ActividadDef(model As ActividadDefaultModel) As JsonResult
            'Try
            '    If Not ModelState.IsValid Then
            '        Return Json(New With {.Result = "ERROR", _
            '                              .Message = My.Resources.ErrorMessageResources.Error_InvalidForm})
            '    Else
            '        Dim db As New SchoolClickDB_Repositorio
            '        Dim msjError As String = String.Empty

            '        If db.IActividadesEva.InsertActividadDefault_DataTemp(model.Nombre, model.Porcentaje, model.Editable, msjError) Then
            '            'Agregamos los campos faltantes para que se muestre en la tabla de actividades
            '            model.DescEditable = If(model.Editable, "El Maestro podrá desglosar esta evaluación", "Esta actividad no se podrá desglosar")
            '            model.Num = "+"
            '            model.ID = msjError
            '            model.PorcentajeString = String.Format("{0}%", model.Porcentaje)

            '            Dim AddedRecord = model
            '            Return Json(New With {.Result = "OK", .Record = AddedRecord})
            '        Else
            '            Return Json(New With {.Result = "ERROR", .Message = msjError})
            '        End If
            '    End If
            'Catch ex As Exception
            '    Return Json(New With {.Result = "ERROR", .Message = ex.Message})
            'End Try
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function _Delete_ActividadDef(ID As String) As JsonResult
            'Try
            '    Dim db As New SchoolClickDB_Repositorio
            '    Dim msjError As String = String.Empty
            '    If db.IActividadesEva.DeleteActividadDefault_DataTemp(ID, msjError) Then
            '        Return Json(New With {.Result = "OK"})
            '    Else
            '        Return Json(New With {.Result = "ERROR", .Message = msjError})
            '    End If
            'Catch ex As Exception
            '    Return Json(New With {.Result = "ERROR", .Message = ex.Message})
            'End Try
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function _Update_ActividadDef(model As ActividadDefaultModel) As JsonResult
            'Try
            '    If Not ModelState.IsValid Then
            '        Return Json(New With {.Result = "ERROR", _
            '                              .Message = My.Resources.ErrorMessageResources.Error_InvalidForm})
            '    Else
            '        Dim msjError As String = String.Empty
            '        Dim db As New SchoolClickDB_Repositorio

            '        If db.IActividadesEva.UpdateActividadesDefault_DataTemp(model.ID, model.Nombre, model.Porcentaje, model.Editable, msjError) Then
            '            Return Json(New With {.Result = "OK"})
            '        Else
            '            Return Json(New With {.Result = "ERROR", .Message = msjError})
            '        End If
            '    End If
            'Catch ex As Exception
            '    Return Json(New With {.Result = "ERROR", .Message = ex.Message})
            'End Try
        End Function
#End Region
#End Region

#Region "TODOS LOS METODOS UTILIZADOS PARA EL MENUITEM 'CREAR_GRADOS'"
        <Authorize(Roles:="ERA")> _
        Function Crear_Grados() As ActionResult
            'Dim db As New SchoolClickDB_Repositorio
            'Try
            '    ViewBag.ListAnios = db.IAñosEscolares.GetListOnlyYears
            '    Return View()
            'Catch ex As Exception
            '    Throw New Exception(ex.Message, ex)
            'End Try
        End Function

#Region "CRUDA PARA LA TABLA DE GRADOS"
        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function _Load_Grados(Anio As String) As JsonResult
            'Try
            '    Dim db As New SchoolClickDB_Repositorio
            '    Return Json(New With {.Result = "OK", .Records = db.IGrados.GetListGrados_FormatModel(Anio)})
            'Catch ex As Exception
            '    Return Json(New With {.Result = "ERROR", .Message = ex.Message})
            'End Try
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function _New_Grado(model As GradoModel) As JsonResult
            If ModelState.IsValid Then
                'Try
                '    Dim db As New SchoolClickDB_Repositorio
                '    Dim msjE = String.Empty

                '    If db.IGrados.InsertNewGrado(model.AnioEscolar, model.Grado, model.Especialidad, model.Seccion, model.Cantidad, msjE) Then
                '        model.Seccion = model.Seccion.ToUpper
                '        Return Json(New With {.Result = "OK", .Record = model})
                '    Else
                '        Return Json(New With {.Result = "ERROR", .Message = msjE})
                '    End If
                'Catch ex As Exception
                '    Return Json(New With {.Result = "ERROR", .Message = ex.Message})
                'End Try
            Else
                Return Json(New With {.Result = "OK", .Message = "No todos los datos son validos, no se puede almacenar el grado."})
            End If
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function _Delete_Grado(ID As String) As JsonResult
            Try
                'Dim db As New SchoolClickDB_Repositorio
                'Dim msjError As String = String.Empty
                'If db.IGrados.DeleteGrado(ID, msjError) Then
                '    Return Json(New With {.Result = "OK"})
                'Else
                '    Return Json(New With {.Result = "ERROR", .Message = msjError})
                'End If
            Catch ex As Exception
                Return Json(New With {.Result = "ERROR", .Message = ex.Message})
            End Try
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function _Update_Grado(model As GradoModel) As JsonResult
            Try
                'If Not ModelState.IsValid Then
                '    Return Json(New With {.Result = "ERROR", _
                '                          .Message = My.Resources.ErrorMessageResources.Error_InvalidForm})
                'Else
                '    Dim msjError As String = String.Empty
                '    Dim db As New SchoolClickDB_Repositorio

                '    If db.IGrados.UpdateGrado(model.ID, model.Grado, model.Especialidad, model.Seccion, msjError) Then
                '        Return Json(New With {.Result = "OK"})
                '    Else
                '        Return Json(New With {.Result = "ERROR", .Message = msjError})
                '    End If
                'End If
            Catch ex As Exception
                Return Json(New With {.Result = "ERROR", .Message = ex.Message})
            End Try
        End Function
#End Region
#End Region

#Region "TODOS LOS METODOS UTILIZADOS PARA EL MENUITEM 'MATERIAS_DEL_INSTITUTO'"
        <Authorize(Roles:="ERA")> _
        Function Materias() As ActionResult
            Dim db As New SchoolClickDB_Repositorio
            'Try
            '    'Recuperamos el Listado de Grupos de Gardos
            '    ViewBag.ListGroupGrados = db.IGroupGrados.GetListItem
            '    Return View()
            'Catch ex As Exception
            '    Throw New Exception(ex.Message, ex)
            'End Try
        End Function

        <Authorize(Roles:="ERA")> _
        Function _AutoCompleteMaterias(idgroup As Integer, maxRows As Integer, text As String) As JsonResult
            'Dim db As New SchoolClickDB_Repositorio
            'Dim var = db.IMateriasDefault.GetMateriasAutoCompleted(idgroup, maxRows, text)
            'Return Json(var)
        End Function

#Region "CRUDA PARA LA TABLA DE MATERIAS DE LOS GROUP GRADOS"
        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function _Load_MateriasDef(IDGroup As Integer) As JsonResult
            'Try
            '    Dim db As New SchoolClickDB_Repositorio
            '    Return Json(New With {.Result = "OK", .Records = db.IMateriasDefault.GetModelByGroupGrado(IDGroup)})
            'Catch ex As Exception
            '    Return Json(New With {.Result = "ERROR", .Message = ex.Message})
            'End Try
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function _New_MateriaDef(model As GroupGradosMateriasModel) As JsonResult
            If ModelState.IsValid Then
                'Try
                '    Dim db As New SchoolClickDB_Repositorio
                '    Dim msjE = String.Empty

                '    If db.IMateriasDefault.AsociarMateriaAlGroupGrado(model.No, model.IDMateria, msjE) Then
                '        model.IDMateria = String.Format("{0}-{1}", model.IDMateria, model.No)
                '        model.No = 0
                '        Return Json(New With {.Result = "OK", .Record = model})
                '    Else
                '        Return Json(New With {.Result = "ERROR", .Message = msjE})
                '    End If
                'Catch ex As Exception
                '    Return Json(New With {.Result = "ERROR", .Message = ex.Message})
                'End Try
            Else
                Return Json(New With {.Result = "OK", .Message = "No todos los datos son validos, no se puede asociar la materia al grupo de grados."})
            End If
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function _Delete_MateriaDef(IDMateria As String) As JsonResult
            'Try
            '    Dim separator As Char() = {"-"}
            '    Dim sSplit As String() = IDMateria.Split(separator)
            '    Dim db As New SchoolClickDB_Repositorio
            '    Dim msjError As String = String.Empty
            '    If db.IMateriasDefault.DeleteAsociacionMateriaAlGroupGrado(sSplit(1), sSplit(0), msjError) Then
            '        Return Json(New With {.Result = "OK"})
            '    Else
            '        Return Json(New With {.Result = "ERROR", .Message = msjError})
            '    End If
            'Catch ex As Exception
            '    Return Json(New With {.Result = "ERROR", .Message = ex.Message})
            'End Try
        End Function
        
#End Region
#End Region

#Region "TODOS LOS METODOS UTILIZADOS PARA EL MENUITEM 'VINCULAR MATERIAS A PROFESORES'"
        <Authorize(Roles:="ERA")> _
        <HttpGet()> _
        Function Vincular_Materias_Profesores() As ActionResult
            'Dim db As New SchoolClickDB_Repositorio
            'Try
            '    'Recuperamos el Listado de Grupos de Gardos
            '    ViewBag.ListGroupGrados = db.IGroupGrados.GetListItem
            '    ViewBag.ListAnios = db.IAñosEscolares.GetListOnlyYears
            '    Return View()
            'Catch ex As Exception
            '    Throw New Exception(ex.Message, ex)
            'End Try
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function _ListGrados_ByGroupAndAnio(IDGroup As Integer, Anio As String) As JsonResult
            Dim db As New SchoolClickDB_Repositorio
            'Try
            '    'Recuperamos el Listado de Grupos de Gardos
            '    Dim datos = db.IGrados.GetGrados_ByGroupAndAnio_FormatCheckList(IDGroup, Anio)
            '    Return Json(New With {.Result = True, .Records = datos, .Count = datos.Count})
            'Catch ex As Exception
            '    Return Json(New With {.Result = False, .Mensaje = ex.InnerException.Message})
            'End Try
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function _ListMaterias(IDGroup As Integer) As JsonResult
            Dim db As New SchoolClickDB_Repositorio
            'Try
            '    'Recuperamos el Listado de Grupos de Gardos
            '    Dim datos = db.IMateriasDefault.GetMaterias_ByAsignacion(IDGroup)
            '    Return Json(New With {.Result = True, .Records = datos, .Count = datos.Count})
            'Catch ex As Exception
            '    Return Json(New With {.Result = False, .Mensaje = ex.InnerException.Message})
            'End Try
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function _ListComboBoxProfesores() As JsonResult
            Dim db As New SchoolClickDB_Repositorio
            Try
                'Recuperamos el Listado de Grupos de Gardos
                'Dim datos = db.IProfesores.GetProfesores_FormatDictionary
                'Return Json(New With {.Result = True, .Records = datos})
            Catch ex As Exception
                Return Json(New With {.Result = False, .Mensaje = ex.InnerException.Message})
            End Try
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function _SaveAll_Vincul_MatProfGrad(aG As List(Of String), aM As List(Of String)) As JsonResult
            Dim db As New SchoolClickDB_Repositorio
            Dim separator As Char() = {"-"}
            Dim msjE As String = String.Empty
            Dim strInfoMat As String()

            'Try

            '    'PRIMERO: Vamos a recorrer uno por los grados en los cuales debemos de asignar el profesor a la materia
            '    For Each g In aG
            '        'Dentro de cada grado, debemos de recorrer cada una de las materias para ir insertando cada registro
            '        For Each m In aM
            '            'Separamos el Codigo de Materia y el Profesor seleccionado
            '            strInfoMat = m.Split(separator)
            '            db.IGradosProfesorMateria.AddAsociacionMatPrfGrd(g, strInfoMat(0), strInfoMat(1), msjE)
            '        Next
            '    Next

            '    If msjE.Equals(String.Empty) Then
            '        Return Json(New With {.Success = True, .Message = "Se guardaron correctamente todas las asociaciones del profesor a la materia en los grados especificados.", .Desactivar = False})
            '    Else
            '        Response.StatusCode = HttpStatusCode.InternalServerError
            '        Return Json("Algunas asociaciones no se pudieron guardar debido a un problema interno con el servidor, por favor vuelva a intentarlo.")
            '    End If
            'Catch ex As Exception
            '    Response.StatusCode = HttpStatusCode.InternalServerError
            '    Return Json(ex.InnerException.Message)
            'End Try
        End Function

        <Authorize(Roles:="ERA")> _
        <HttpPost()> _
        Function _ViewAsociacionesMPG(Titulo As String, IDGroup As Integer, Anio As Integer) As ActionResult
            Dim db As New SchoolClickDB_Repositorio

            'Try
            '    Dim dataGrados = db.IGrados.GetGrados_ByGroupAndAnio(IDGroup, Anio)
            '    ViewBag.Titulo = String.Format("{0} - Secciones", Titulo)
            '    ViewBag.CountGrados = dataGrados.Count + 1
            '    ViewBag.ListGrados = dataGrados
            '    ViewBag.ListMaterias = db.IGradosProfesorMateria.GetTablaAsociaciones(IDGroup, Anio)
            '    Return PartialView()
            'Catch ex As Exception
            '    Response.StatusCode = HttpStatusCode.InternalServerError
            '    Return Json(ex.InnerException.Message)
            'End Try
        End Function
#End Region

#Region "TODOS LOS METODOS UTILIZADOS PARA EL MENUITEM 'DISTRIBUIR_ALUMNOS_GRADOS'"
        <Authorize(Roles:="ERA")> _
        <HttpGet()> _
        Function Distribuir_Alumnos() As ActionResult
            'Dim db As New SchoolClickDB_Repositorio
            'Try
            '    'Recuperamos el Listado de Grupos de Gardos
            '    ViewBag.ListGroupGrados = db.IGroupGrados.GetListItem
            '    ViewBag.ListAnios = db.IAñosEscolares.GetListOnlyYears
            '    Return View()
            'Catch ex As Exception
            '    Throw New Exception(ex.Message, ex)
            'End Try
        End Function
#End Region

    End Class


End Namespace
